import React, {useState, useEffect} from 'react';
import {withRouter} from 'react-router-dom';
import {List, ListView, SearchBar, NavBar, Icon, Toast} from 'antd-mobile';
import {R} from "@/assets/js/dict"
import _ from 'lodash';
import {getHistoryOrdersOfParent} from "@/api/order/order.js";

const Item = List.Item;
const Brief = Item.Brief;

const data = [
    {
        img: 'https://zos.alipayobjects.com/rmsportal/dKbkpPXKfvZzWCM.png',
        title: 'Meet hotel',
        des: '不是所有的兼职汪都需要风吹日晒',
    },
    {
        img: 'https://zos.alipayobjects.com/rmsportal/XmwCzSeJiqpkuMB.png',
        title: 'McDonald\'s invites you',
        des: '不是所有的兼职汪都需要风吹日晒',
    },
    {
        img: 'https://zos.alipayobjects.com/rmsportal/hfVtzEhPzTUewPm.png',
        title: 'Eat the week',
        des: '不是所有的兼职汪都需要风吹日晒',
    },
];
const NUM_ROWS = 20;
let pageIndex = 0;

function genData(pIndex = 0) {
    const dataBlob = {};
    for (let i = 0; i < NUM_ROWS; i++) {
        const ii = (pIndex * NUM_ROWS) + i;
        dataBlob[`${ii}`] = `row - ${ii}`;
    }
    return dataBlob;
}

function Demo(props) {

    let [userInfo] = useState(() => {
        let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
        return userInfo
    });
    let [dataSource, setDataSource] = useState(new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
    }));

    let [orders, setOrders] = useState([]);

    //后台返回的分页数据
    let [records, setRecords] = useState({});

    let [word, setWord] = useState("加载中...");
    let [isLoading, setisLoading] = useState(true);

    function getOrders(pageNum, pageSize=5) {
        getHistoryOrdersOfParent({parent_id: userInfo.id, pageNum: pageNum, pageSize: pageSize}, (re) => {
            if (R.isSuccess(re)) {
                let data = R.getData(re);
                if (!!data.dataList && data.dataList.length > 0) {
                    setRecords(data);
                    orders.push(...data.dataList);
                    setOrders(orders);
                    let d = dataSource.cloneWithRows(orders);
                    setDataSource(d);
                    setWord("已加载");
                } else {
                    setWord("亲，没有更多了");
                }
                setisLoading(false);
            }
        })
    }

    useEffect(() => {
        // alert("useEffect--------->")
        getOrders(1);
    }, []);

    let onEndReached = (event) => {
        // load new data
        // hasMore: from backend data, indicates whether it is the last page, here is false
        if (isLoading || records.pageIndex === records.totalPage) {
            setWord("亲，没有更多了");
        } else {
            setisLoading(true);
            setWord("加载中...");
            getOrders(records.pageIndex + 1);
        }
    };

    const separator = (sectionID, rowID) => (
        <div
            key={`${sectionID}-${rowID}`}
            style={{
                backgroundColor: '#F5F5F9',
                height: 8,
                borderTop: '1px solid #ECECED',
                borderBottom: '1px solid #ECECED',
            }}
        />
    );

    const row = (rowData, sectionID, rowID) => {
        return (
            <div key={rowID} style={{padding: '0 15px'}}>
                <Item key={rowData.id}
                      arrow="horizontal"
                      multipleLine
                      onClick={() => {
                          console.log("item-->", rowData);
                      }}
                      platform="cross"
                >
                    订单编号：{rowData.code}
                    <Brief> 辅导科目：{rowData.subjects}</Brief>
                    <Brief> 中介费：{rowData.brokerage_fee ? rowData.brokerage_fee / 100 : 0}¥</Brief>
                    <Brief> 更新时间：{rowData.update_time}</Brief>
                </ Item>
            </div>
        );
    };
    return (
        <div>
            <div className="page-title  home-tit">
                <NavBar
                    mode="light"
                    icon={<Icon type="left"/>}
                    leftContent={<span key={"99"}>返回</span>}

                    onLeftClick={() => {
                        props.history.goBack()
                    }}
                >
                    历史订单
                </NavBar>
            </div>

            <div className="page-content  home-content">
                <div className="publish-content-piece">
                    <SearchBar
                        placeholder="搜索"
                        onSubmit={(val) => {
                            console.log("onSubmit", val);
                            getOrders(1, 5);
                        }}
                        onChange={(val) => console.log("onChange", val)}
                        onClear={() => {
                            console.log('onClear');
                        }}
                        onCancel={() => {
                            console.log('onCancel');
                        }}
                    />

                    <ListView
                        dataSource={dataSource}
                        renderFooter={() => (<div style={{padding: 30, textAlign: 'center'}}>
                            {word}
                        </div>)}
                        renderRow={row}
                        renderSeparator={separator}
                        className="am-list"
                        pageSize={4}
                        useBodyScroll
                        onScroll={() => {
                            console.log('scroll');
                        }}
                        scrollRenderAheadDistance={500}
                        onEndReached={onEndReached}
                        onEndReachedThreshold={10}
                    />

                </div>
            </div>
        </div>

    );

}

export default withRouter(Demo);